<?php

namespace app\index\controller;

use think\Cache;
use think\Controller;
use think\Db;
use think\Loader;
use think\Request;
use think\Session;
use think\Validate;
use tree\Tree;

class Index extends Controller
{
    public function testUrl()
    {
        $input = Request()->param();

        // 网页地址
        $url = $input['url'];

        if (empty($url)) apiReturn(2, '请输入问卷预览地址');

        // 使用 file_get_contents 获取网页内容
        $html = @file_get_contents($url);

        if ($html === false) apiReturn(2, '无法获取网页内容');

        // 检查 DOMDocument 类是否可用
        if (!class_exists('DOMDocument')) apiReturn(2, 'DOMDocument 类未找到。请启用 PHP 的 DOM 扩展。');

        // 初始化 DOMDocument 并加载 HTML
        $dom = new \DOMDocument();
        libxml_use_internal_errors(true);
        $loaded = $dom->loadHTML($html, LIBXML_NOERROR | LIBXML_NOWARNING);
        libxml_clear_errors();

        if (!$loaded) apiReturn(2, '无法解析 HTML 内容');

        // 使用 DOMXPath 来查询特定部分的内容
        $xpath = new \DOMXPath($dom);

        // 找到 id="fieldset1" 的部分
        $fieldset = $xpath->query('//*[@id="fieldset1"]')->item(0);

        if (!$fieldset) apiReturn('未找到 id="fieldset1" 的部分');

        $questions = [];

        // 查询所有的 "field" div
        foreach ($xpath->query('.//div[contains(@class, "field")]', $fieldset) as $fieldDiv) {
            // 获取问题的文本
            $questionDiv = $xpath->query('.//div[@class="field-label"]', $fieldDiv)->item(0);
            if (!$questionDiv) {
                continue; // 如果没有找到问题，跳过
            }
            $questionText = trim($questionDiv->textContent);

            // 初始化答案数组
            $answers = [];

            // 查找包含答案选项的 "ui-controlgroup" div
            $controlGroupDiv = $xpath->query('.//div[contains(@class, "ui-controlgroup")]', $fieldDiv)->item(0);
            if ($controlGroupDiv) {
                // 查找所有的 "div.label" 元素作为答案选项
                foreach ($xpath->query('.//div[@class="label"]', $controlGroupDiv) as $answerDiv) {
                    $answerText = trim($answerDiv->textContent);
                    if (!empty($answerText)) {
                        $answers[] = $answerText;
                    }
                }
            }

            // 将问题和答案加入数组
            $questions[] = [
                'question' => $questionText,
                'answers' => $answers
            ];
        }

        apiReturn(1, '获取数据成功', $questions);

    }

    public function index()
    {
        $sign = 'PfCMcW5';
        $list = Db::name('message')->where(['sign' => $sign])->order('id asc')->select();
        $this->assign('list', $list);

        return $this->fetch();
    }

    public function userTextPrompt()
    {
        $input = Request()->param();

        $sign = $input['sign'];
        $prompt = $input['prompt'];

        if (empty($sign)) apiReturn(2, '唯一标识缺失');
        if (empty($prompt)) apiReturn(2, '请输入内容');

        $default_prompt = '我是问卷调查助手，我可以随机帮你生成答案';
        $first_messages = [
            [
                'role' => 'system',
                'content' => $default_prompt
            ]
        ];

        $list = Db::name('message')->field('id,prompt,text')->where(['sign' => $sign])->order('id asc')->select();
        $history_messages = [];
        if ($list) {
            foreach ($list as &$v) {
                $history_messages[] = [
                    'role' => 'user',
                    'content' => $v['prompt']
                ];
                $history_messages[] = [
                    'role' => 'assistant',
                    'content' => $v['text']
                ];
            }
        }

        $prompt_messages = [
            [
                'role' => 'user',
                'content' => $prompt
            ]
        ];

        $messages = array_merge($first_messages, $history_messages, $prompt_messages);
        $data = textGeneration($messages);
        if ($data) {
            $text = $data['output']['text'];
            $request_id = $data['request_id'];

            if ($prompt && $text) {
                $insert_data = [
                    'sign' => $sign,
                    'prompt' => $prompt,
                    'text' => $text,
                    'request_id' => $request_id,
                    'create_time' => time()
                ];
                Db::name('message')->insert($insert_data);

                $new_messages = [
                    'role' => 'assistant',
                    'content' => $text
                ];

                apiReturn(1, '获取数据成功', $new_messages);
            } else {
                apiReturn(2, '获取数据失败');
            }
        } else {
            apiReturn(2, '获取数据失败');
        }
    }

    public function test6()
    {
        sleep(60);
        echo 1;
        exit;
    }

    public function test7()
    {
        $info = Db::name('question')->where(['id' => 21])->find();

        // 设置概率数据
        $probabilities = [
            [80, 10, 10, 0], // 第一题概率
            [50, 30, 10, 10], // 第二题概率
            [40, 30, 30], // 第三题概率
            // [30, 40, 20, 10], // 第四题概率
        ];

        $question = json_decode($info['question'], true);
        $numberOfResponses = 10; // 生成的回答数量

        // 统计每个选项被选中的次数
        $optionCounts = array_fill(0, count($probabilities), array_fill(0, count($probabilities[0]), 0));

        $allResponses = generateAnswers($question, $numberOfResponses, $probabilities);

        foreach ($allResponses as $responses) {
            foreach ($responses as $questionIndex => $response) {
                if (is_array($response)) {
                    foreach ($response as $selectedOption) {
                        $optionCounts[$questionIndex][$selectedOption - 1]++; // 选中次数加1，注意数组下标从0开始
                    }
                } else {
                    $optionCounts[$questionIndex][$response - 1]++; // 单选情况
                }
            }
        }

        // 输出结果
        echo "<pre>";
        print_r(json_encode($allResponses)); // 输出生成的答案
        print_r($optionCounts);              // 输出每道题各选项被选中的次数
        exit;
    }

}
